$(function() {
	removeUnnecessaryMoreButton();

    var index_selected = function(className){
        var num = $(className).length>0 ? $(className).find("a.selected").parent().index() : 0;
        return num;
    }(".swiper-container");
    if(Swiper){
	    var swiper = new Swiper('.swiper-container', {
	        pagination: '.swiper-pagination',
	        nextButton: '.swiper-button-next',
	        prevButton: '.swiper-button-prev',
	        slidesPerView: 3,
	        slidesPerColumn: 1,
	        paginationClickable: true,
	        watchSlidesProgress : true,
	        spaceBetween: 1,
	        preventClicks: false,
	        initialSlide: index_selected
	    });
    }
    // 图片延迟加载
    if ($("img.lazy").length > 0) {
        $img = $("img.lazy");

		function imgSrc() {
			$img.each(function(index, elem) {
				if ($(window).scrollTop() + $(window).height() >= $(elem)
						.offset().top) {
					$(elem).attr("src", $(elem).attr("data-original"));
				}
			});
		}
		imgSrc();
		$("body").on("click", ".country_box span", function() {
			var t_i = $(this).index();
			$img = $(".sDiv").eq(t_i).find("img.lazy");
			imgSrc();
		});
		$img.lazyload({
			effect : "fadeIn"
		});
	}
	if(navigator.userAgent.indexOf("MSIE 8.0") > 0 || navigator.userAgent.indexOf("MSIE 7.0") > 0 || navigator.userAgent.indexOf("MSIE 6.0") > 0 ){
		$("img").each(function(){
			$(this).attr("src",$(this).attr("data-original"));
		});
	}
	// 购物车显示
	if (parseInt($(".headerCartItemsCount").text()) > 0) {
		$(".headerCartItemsCount").parent('#cartLink').addClass("cart_have");
	} else {
		$(".headerCartItemsCount").parent('#cartLink').removeClass("cart_have");
	}
	// 执行banner
	// 主页banner
	if ($("#banners").is(":visible")) {
		var glide = $('.slider').glide({
			animationTime : 2000,
			autoplay : 6000,
			// animationTimingFunc: 'cubic-bezier(0.185, 0.840, 0.440, 1.000)'
			animationTimingFunc : 'ease-in-out'
		}).data('api_glide');
	}
	if ($("#paymentNew").length > 0) {
		$("body").on("click", "#paymentNew", function() {
			$(".mark").show();
			$("#payYes").show();
			zhuge.track('点击去支付',
					{
					});
		});
		$("body").on("click", ".py_close", function() {
			$(".mark").hide();
			$("#payYes").hide();
		});
	}

	// banner
	if ($('.flexslider').length > 0) {
		$('.flexslider').flexslider({
			animationLoop : true,
			directionNav : true,
			pauseOnAction : true,
			pauseOnHover : true,
			easing : 'easeOutExpo'
		});
		if ($('.slides').find("li").length > 1) {
			$('.flexslider').hover(function() {
				$(".flex-direction-nav a").addClass('show');
			}, function() {
				$(".flex-direction-nav a").removeClass('show');
			});
		}
	}
	// 主页切换列表显示模式
	var products = $("#products");
	if (products.length > 0) {
		$("#model_v,#model_h").on("click", function(event) {
			$(this).addClass("active").siblings().removeClass("active");
			products.toggleClass("list_h");
		});
	}

	// 切换频道导航样式
	function activeClass(divEle, currentEle, className) {
		if ($(divEle).length > 0) {
			$(divEle).find(currentEle).each(
					function(index, elem) {
						if ($(elem).attr("href") == window.location.pathname) {
							var nav_bg = window.location.pathname;
							$(elem).addClass(className).parent().siblings()
									.children(currentEle)
									.removeClass(className);
						}
					});
		}
	}
	activeClass("#account-menu", "a", "active_menu"); // 个人信息管理切换
	activeClass(".help_menu", "a", "active_menu"); // 帮助中心

	// 图列表图片处理居中办法
	function fadeIn(obj) {
		$(obj).css('opacity', 0).show().animate({
			opacity : 1
		}, 1000);
	}
	// 产品详情页小图片滑动
	if (!checkStation()) {
		if ($("#product_thumbs_container").length > 0) {
			$("#product_thumbs_container").slide({
				mainCell : ".thumbs_list ul",
				autoPage : true,
				effect : "top",
				prevCell : ".thumb_prev",
				nextCell : ".thumb_next",
				autoPlay : false,
				pnLoop : false,
				prevStop : ".disable",
				nextStop : ".disable",
				vis : 4
			});
		}
	}
	// 产品信息
	if ($('#product_content').length > 0) {
		var numDiv = $("#changeNum");
		var inputNum = numDiv.find("input[type='text']");
		var num = inputNum.val();
		inputNum.on('blur', function() {
			if (/^\+?[1-9][0-9]*$/.test(inputNum.val())) {
				num = inputNum.val();
				inputNum.val(num);
			} else {
				num = this.defaultValue;
				inputNum.val(num);
			}
			$("#atc_num").val(num);
		});
		numDiv.find("a").on("click", function() {
			num = parseInt(inputNum.val());
			if ($(this).hasClass("add")) {
				numDiv.find("a").removeClass("forbid");
				num++;
			} else if ($(this).hasClass("sub")) {
				numDiv.find("a").removeClass("forbid");
				if (num <= 1) {
					$(this).addClass("forbid");
					num = 1;
				} else {
					num--;
				}
			} else {
				num = parseInt(inputNum.val());
			}
			inputNum.val(num);
			$("#atc_num").val(num);
			return false;
		});
		// 选择款式
		var style = $("#selected_style");
		style.find("span").on(
				"click",
				function() {
					if ($(this).hasClass("no_store"))
						return false;
					$(this).addClass("style_checked").siblings().removeClass(
							"style_checked");
					return false;
				});
		var color = $("#selected_color");
		color.find("a").on("click", function() {
			if ($(this).hasClass("no_store"))
				return false;
			$(this).addClass("checked").siblings().removeClass("checked");
			return false;
		});
		// 选择颜色
	}
	// 产品详情tab
	if ($('#pro_tab').length > 0) {
		var index;
		var tab = $('#pro_tab');
		var tabfix = tab.find(".place_tab");
		var tabTop = tabfix.offset().top;
		var srlTop;
		var temp = $("#header_content").height();

		function switchClass(parent, item, className, index) {
			$(parent).find(item).removeClass(className);
			$(parent).find(item).eq(index).addClass(className);
		}
		tab.find(".place_tab li").on("click", function() {
			index = $(this).index();
			switchClass(tab, ".place_tab a", "tab_cur", index);
			switchClass(tab, ".p_tab", "tab_cur", index);
		});
		$(window).on(
				"scroll",
				function() {
					srlTop = $(window).scrollTop();
					if (browser.versions.mobile || browser.versions.android
							|| browser.versions.ios) {
						if (srlTop > tabTop - temp) {
							tabfix.css({
								"position" : "fixed",
								"top" : temp + 'px'
							});
						} else if (srlTop <= tabTop - temp) {
							tabfix.css({
								"position" : "absolute",
								"top" : 0
							});
						}
					} else {
						if (srlTop > tabTop) {
							tabfix.css({
								"position" : "fixed",
								"left" : tabfix.offset().left + "px",
								"top" : "0"
							});
						} else if (srlTop <= tabTop) {
							tabfix.css({
								"position" : "absolute",
								"left" : "0",
								"top" : "0"
							});
						}
					}
				});
	}

	// 奶粉页粘性导航
	if ($(".subMenu").length > 0) {
		var smint = $(".subMenu"), direction = 'down', menuOffset = smint
				.offset().top;
		filterH = $(".fil").length > 0 ? $(".fil").outerHeight(true) : 0;
		var menuHeight = smint.height();
		var allT = menuOffset + filterH + menuHeight;
		var sDiv = $(".sDiv");
		var link = $(".country_box a");
		var srl;
		var index = 0;
		if (browser.versions.mobile || browser.versions.android
				|| browser.versions.ios) {
			// console.log("移动端")
			sDiv.hide();
			link.eq(index).addClass("active");
			sDiv.eq(index).show();
			link.on("click", function() {
				sDiv.hide();
				$(this).addClass("active").parent().siblings().children("a")
						.removeClass("active");
				index = $(this).parent().index();
				sDiv.eq(index).show();
			})
		} else {
			sDiv.each(function(index, elem) {
				$(elem).addClass(link.eq(index).attr('id'));
			});
			$(window).scroll(
					function() {
						srl = $(window).scrollTop()
						if (srl >= allT) {
							sDiv
									.each(function(index, elem) {
										if (srl > $(elem).offset().top
												&& srl < $(elem).offset().top
														+ $(elem).height()
														- menuHeight) {
											link.eq(index).addClass('active')
													.parent().siblings()
													.children().removeClass(
															'active');
										}
									});
							smint.css({
								'position' : 'fixed',
								'left' : 0,
								'top' : 0
							});
						} else if ($(window).scrollTop() < allT) {
							link.removeClass('active');
							smint.css({
								'position' : 'relative',
								'top' : 0,
								'left' : 0
							});
						}
					});
			link.on('click', function() {
				link.removeClass('active');
				$(this).addClass('active');
				var id = $(this).attr('id');
				$('html,body').animate(
						{
							scrollTop : sDiv.filter('.' + id).offset().top
									+ menuHeight + 10 + "px"
						}, 400);
			});
		}
	}

	// 购物清单 物流信息
	if ($("#address-list").length > 0) {
		var addressList = $("#address-list");
		var radioV;
		var radioIndex;
		addressList.find(".add_list_item").each(function(index, elem) {
			if ($(elem).find("input[type=radio]:checked").val()) {
				$(elem).addClass("checked");
			}
			$(elem).on('click', function() {
				radioV = $(this).find("input[type=radio]:checked").val();
				radioIndex = $(this).index();
				if (radioV != null) {
					addressList.find(".add_list_item").removeClass("checked");
					$(this).addClass("checked");
				}
			});
		})
	}

	// 夺宝
	if ($(".surplus").length > 0) {
		var rep = $(".rep");
		function eachItem(elem) {
			var surplus;
			var total;
			var percent;
			surplus = parseFloat($(elem).find("#rep_surplus").text());
			total = parseFloat($(elem).find("#rep_total").text());
			percent = 100 - parseFloat((surplus / total) * 100);
			if (percent > 99 && percent < 100) {
				percent = 99;
			} else if (percent > 0 && percent < 1) {
				percent = 1;
			}
			return percent;
		}
		if (browser.versions.mobile || browser.versions.android
				|| browser.versions.ios) {
			rep.each(function(index, elem) {
				$(elem).find(".rep_mark").css("width", eachItem(elem) + "%");
			});
		} else {
			$(window).on("load", function() {
				rep.each(function(index, elem) {
					$(elem).find(".rep_mark").animate({
						"width" : eachItem(elem) + "%"
					}, 1000, "easeOutQuad");
				});
			});
		}
	}
	if ($(".cont").length > 0) {
		var info = navigator.userAgent;
		if (info.indexOf("iPod") != -1 || info.indexOf("iPad") != -1
				|| info.indexOf("iPhone") != -1
				|| info.indexOf("Android") != -1) {
			// alert("平板");
			$(".cont h2").click(function() {
				$(this).toggleClass("unfold");
				$(this).siblings(".tgl_cont").toggle();
			});
		} else {
			// alert("电脑");
			$(window).load(function() {
				$("#content-1").mCustomScrollbar({
					theme : "minimal",
					scrollButtons : {
						enable : true
					},
				});
			});
		}
	}
	;
	if ($(".db_pannel").length > 0) {
		var time_temp = $("#deadline").val().split(".");
		time_temp[0] = time_temp[0].replace(/-/g, "/");
		var deadline = new Date(time_temp[0]);
		function timer(deadline) {
			var time_end = new Date(deadline); // 结束的时间
			var time_now = new Date();
			var intDiff = parseInt((time_end.getTime() + parseInt(time_temp[1]) - time_now
					.getTime()) / 1000);
			var day = 0, hour = 0, minute = 0, second = 0;
			var cd_d_1 = $(".cd_d_1"), cd_d_2 = $(".cd_d_2")
			cd_h_1 = $(".cd_h_1"), cd_h_2 = $(".cd_h_2"),
					cd_m_1 = $(".cd_m_1"), cd_m_2 = $(".cd_m_2"),
					cd_s_1 = $(".cd_s_1");
			cd_s_2 = $(".cd_s_2");
			var setInt = setInterval(function() {
				if (intDiff <= 0)
					clearInterval(setInt);
				if (intDiff > 0) {
					day = Math.floor(intDiff / (60 * 60 * 24));
					hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
					minute = Math.floor(intDiff / 60) - (day * 24 * 60)
							- (hour * 60);
					second = Math.floor(intDiff) - (day * 24 * 60 * 60)
							- (hour * 60 * 60) - (minute * 60);
				}
				cd_d_1.html(parseInt(day / 10));
				cd_d_2.html(parseInt(day % 10));
				cd_h_1.html(parseInt(hour / 10));
				cd_h_2.html(parseInt(hour % 10));
				cd_m_1.html(parseInt(minute / 10));
				cd_m_2.html(parseInt(minute % 10));
				cd_s_1.html(parseInt(second / 10));
				cd_s_2.html(parseInt(second % 10));
				intDiff--;
			}, 1000);
		}
		timer(deadline);
	}
	if ($("#product_thumbs_container").length > 0) {
		if (!checkStation()) {
			jQuery(".picScroll-top").slide({
				titCell : ".hd ul",
				mainCell : ".bd ul",
				effect : "topLoop",
				autoPlay : true,
				pnLoop : true,
				interTime : 4000,
				delayTime : 1000,
				loop : true,
				vis : 5
			});
		}
	}
	if ($(".tr_ad").length > 0) {
		(function() {
			if ($.cookie("isClose") != "yes") {
				$(".tr_ad").fadeIn();
				$('body').css("overflow", "hidden");
				$.cookie("isClose", 'yes', {
					expires : 1
				});
				var i = parseInt($("#rest_time").text());
				var rest_time;
				$(window).on("load", function() {
					rest_time = setInterval(function() {
						i--;
						$("#rest_time").html(i);
						if (i == 0) {
							clearInterval(rest_time);
							$(".tr_ad").fadeOut();
							$('body').css("overflow", "visible");
						}
					}, 1000);
				});
				$("body").on("click", ".tr_close", function() {
					$(".tr_ad").fadeOut();
					$('body').css("overflow", "visible");
				})
			}
		})();
	}

	// 帮助中心
	if ($(".help_menu").length > 0) {
		$(".help_menu dt").on('click', function() {
			$(this).find('i').toggleClass("fold");
			$(this).siblings("dd").slideToggle("fast");
		});
	}

	if ($("#u-arr").length > 0) {
		$("#u-arr a").click(function() {
			$("html,body").animate({
				scrollTop : $(".rule_cont_box").offset().top
			}, 700);
		});
		$(window)
				.scroll(
						function() {
							if ($(window).scrollTop() > $(".rule_cont_box")
									.offset().top
									- $(window).height()) {
								$("#u-arr").fadeOut(500);
							} else {
								$("#u-arr").fadeIn(500);
							}
						});
	}
	// 回到顶部
	$(window).on("scroll", function() {
		if ($(this).scrollTop() > 200) {
			$(".siderbar").fadeIn(1000)
		} else {
			$(".siderbar").fadeOut(1000)
		}
	});
	$(".overTop").click(function() {
		$("html,body").animate({
			scrollTop : 0
		}, 500);
	})

	// mobile
	// 获取页面滚动条位置
	var getPage = function() {
		var dd = document.documentElement, db = document.body;
		return {
			left : Math.max(dd.scrollLeft, db.scrollLeft),
			top : Math.max(dd.scrollTop, db.scrollTop)
		};
	};


    // 回到顶部
    $(window).on("scroll", function() {
        if ($(this).scrollTop() > 200) {
            $(".siderbar").fadeIn(1000)
        } else {
            $(".siderbar").fadeOut(1000)
        }
    });
    $(".overTop").click(function() {
        $("html,body").animate({
            scrollTop: 0
        }, 500);
    });
    // 获取海外潮品优惠码
    $(".promote_activity").each(function(){
        var count = 8;
        var moov_time;
        if(checkStation()){
            var _divH = $(".show_promote_info").width();
            $(this).find(".show_pro_info_center").css("height",_divH);
        }

        $(this).find(".promote_btn_close").on("click",function(){
            $(".promote_box").hide();
        });
        $(this).find(".get_promote").on("click",function(){
            $("#moov_time").remove();
            if(moov_time){
            	clearInterval(moov_time);
            }
            $(".show_promote_info").fadeIn(function(){
                $(this).find(".show_pro_info_center").addClass("active");
            });
        });
        $(this).find(".promote_close").on("click",function(){
            $(".show_promote_info").fadeOut(function(){
                $(this).find(".show_pro_info_center").removeClass("active");
            });
        });
        var url = window.location.pathname;
        var limit_urls = ["/","/shop/","/shop/overseas"];
        if($.inArray(url, limit_urls, 0) > -1){
            if ($.cookie("moov") != "yes") {
                $(".show_promote_info").fadeIn(function(){
                    $(this).find(".show_pro_info_center").addClass("active");
                });
                $(".show_pro_info_center").append($("<span id='moov_time'></span>"));
                moov_time = setInterval(function() {
                    $("#moov_time").html(count);
                    if (count == 0) {
                        clearInterval(moov_time);
                        $(".show_promote_info").fadeOut(function(){
                            $(".show_pro_info_center").removeClass("active");
                            $("#moov_time").remove();
                        });
                    }
                    count--;
                }, 1000);
                $.cookie("moov", 'yes', {
                    expires : 1/12,
                    path:'/'
                });
            }
        }
    });


    // mobile
    // 获取页面滚动条位置
    var getPage = function() {
        var dd = document.documentElement,
            db = document.body;
        return {
            left: Math.max(dd.scrollLeft, db.scrollLeft),
            top: Math.max(dd.scrollTop, db.scrollTop)
        };
    };

    // 下拉
    var flagTemp = true;
    var tglClass = function(abtn, active, target, tactive) {
            var mark = ($(".black_mark").length > 0) ? $(".black_mark") : null;
            mark.on("click", function() {
                lock.close();
                $(abtn).removeClass(active);
                $(target).removeClass(tactive);
                mark.hide();
                flagTemp = true;
            });
            $(abtn).on('click', function(e) {
                e.targetTouches = false;
                e.preventDefault();
                if (flagTemp) {
                    if ($(this).hasClass(active)) {
                        $(this).removeClass(active);
                        $(target).removeClass(tactive);
                        mark.hide();
                        lock.close();
                    } else {
                        $(this).addClass(active);
                        $(target).addClass(tactive);
                        mark.show();
                        lock.show();
                    }
                    flagTemp = false;
                    return true;
                } else if (!flagTemp) {
                    if ($(this).hasClass(active)) {
                        $(this).removeClass(active);
                        $(target).removeClass(tactive);
                        mark.hide();
                        lock.close();
                        flagTemp = true;
                    }
                }
            });
        };
        //mobile 搜索框
    if ($(".p_h_search").is(":visible")) {
        tglClass(".p_h_search", "active", ".drop_search", "d_show");
    }
    //mobile 用户中心
    if ($(".ic_user").is(":visible")) {
        tglClass(".ic_user", "active", ".log_r", "drop");
    }
    if ($("#M_carte").length > 0) {
        $("body").on('click', "#M_carte", function(e) {
            $(this).toggleClass("on");
            $(".manage-account-container").toggleClass("drag");
        });
    }

    $('input#reg_cb').click(function() {
    	if($('#reg_cb').is(":checked")) {
    		$("#check_tos").hide();
    	}
    });
    $('a.terms_of_service').click(function(){
        lock.close();
        $("#pageOverlay").show();
        $('#div_tos').show();
    	return false;
    });
    $('#service-close').click(function() {
        $("#pageOverlay").hide();
        $('#div_tos').hide();
        return false;
    });
    $("#pageOverlay").on("click",function(){
        $('#div_tos').hide();
    });
    $('body').on('click', 'input#reg_btn', function() {
    	if (!$('#reg_cb').is(":checked")) {
    		$("#check_tos").css('display', 'block');
    		return false;
    	}
    	return true;
    });
    // 设置记住密码cookie
    (function(){
	    if ($.cookie("rememberPassword") == "true") {
	        $("#rememberPassword").attr("checked", true);
	        $("input[name='j_username'").val($.cookie("userName"));
	        // $("input[name='j_password'").val($.cookie("passWord"));
	    }
		$(".login_button").on("click",function() {
		    if ($("#rememberPassword").is(":checked")) {
		        var userName = $("input[name='j_username'").val();
		        var passWord = $("input[name='j_password'").val();
		        $.cookie("rememberPassword", "true", { expires: 7 }); // 存储一个带7天期限的 cookie
		        $.cookie("userName", userName, { expires: 7 }); // 存储一个带7天期限的 cookie
		        // $.cookie("passWord", passWord, { expires: 7 }); // 存储一个带7天期限的 cookie
		    } else {
		        $.cookie("rememberPassword", "false", { expires: -1 }); // 删除 cookie
		        $.cookie("userName", '', { expires: -1 });
		        // $.cookie("passWord", '', { expires: -1 });
		    }
		});
    })();

});

function showMoreFilterConditions(obj){
	if("更多"==obj.children().text()){
		obj.parent().parent().css("height","auto");
		obj.children().text("收起");
	}
	else{
		obj.children().text("更多");
		obj.parent().parent().css("height","24px");
	}

}

 function removeUnnecessaryMoreButton(){
    	 $(".section ul").each(function(){
    	 		var li_total_width = 0;
    	 		$(this).children().each(function(){
    	 				li_total_width += $(this).width() + 10;
    	 		});
    	 		if(li_total_width < $(this).width()){
    	 			$(this).parent().find(".more").css("display","none");
    	 		}
          });

};
